package com.stox.core.dao.mapper;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.stox.core.model.Exchange;

public class ExchangeRowMapper implements RowMapper<Exchange> {

	public static final String createSql =  "create table exchange(" +
			"code varchar(20) not null," +
			"name varchar(100) not null," +
			"lastTradingDate date," +
			"country varchar(50) not null," +
			"flagImage varchar(50) not null," +
			"ftdc boolean not null, " +
			"configured boolean not null," +
			"primary key(code))";
	public static final String selectSql = "select e.code, e.name,  e.lastTradingDate, e.country, e.flagImage, e.ftdc, e.configured from Exchange e ";
	public static final String insertSql = "insert into exchange(code, name, lastTradingDate, country, flagImage, ftdc, configured) values(?,?,?,?,?,?,?)";
	
	@Override
	public List<Exchange> map(ResultSet rs) throws SQLException {
		List<Exchange> exchanges = new ArrayList<Exchange>();
		while(rs.next()){
			Exchange exchange = new Exchange();
			exchange.setCode(rs.getString("code"));
			exchange.setName(rs.getString("name"));
			exchange.setLastTradingDate(new java.util.Date(rs.getDate("lastTradingDate").getTime()));
			exchange.setCountry(rs.getString("country"));
			exchange.setFlagImage(rs.getString("flagImage"));
			exchange.setFirstTimeDownloadCompleted(rs.getBoolean("ftdc"));
			exchange.setConfigured(rs.getBoolean("configured"));
			exchanges.add(exchange);
		}
		return exchanges;
	}
	
	@SuppressWarnings("deprecation")
	public void map(PreparedStatement ps, Exchange exchange) throws SQLException{
		ps.setString(1, exchange.getCode());
		ps.setString(2, exchange.getName());
		if(exchange.getLastTradingDate() != null){
			ps.setDate(3, new Date(exchange.getLastTradingDate().getTime()));
		}else{
			ps.setDate(3, new Date(109, 0, 1));
		}
		ps.setString(4, exchange.getCountry());
		ps.setString(5, exchange.getFlagImage());
		ps.setBoolean(6, exchange.isFirstTimeDownloadCompleted());
		ps.setBoolean(7, exchange.isConfigured());
	}

}
